using System;
using System.Collections;
using System.Data;

using LocalBoard.Domain;

namespace LocalBoard.Persistence.MockAccessor
{
	/// <summary>
	/// Summary description for MockCommentAccessor.
	/// </summary>
	public class MockCommentAccessor : ICommentAccessor, IMockAccessor
	{
		private int _oId = 0;
		private DataTable _commentTable = new DataTable("Comment");
		public static readonly MockCommentAccessor Instance = 
			new MockCommentAccessor();

		private MockCommentAccessor()
		{
			_commentTable.Columns.Add("Id", typeof(int));
			_commentTable.Columns.Add("Body", typeof(string));
			_commentTable.Columns.Add("PostedByUserName", typeof(string));
			_commentTable.Columns.Add("PostedByUserId", typeof(string));
			_commentTable.Columns.Add("Date", typeof(DateTime));
			_commentTable.Columns.Add("Author_Id", typeof(int));
			_commentTable.Columns.Add("Message_Id", typeof(int));
		}

		public void ResetDataTable()
		{
			_oId = 0;
			_commentTable.Clear();
		}

		public void RemoveRows(int tableIndex, DataRow[] rows)
		{
			throw new NotImplementedException();
		}

		public DataRow[] ExecuteFilter(string filterExpression)
		{
			throw new NotImplementedException();
		}

		#region ICommentAccessor Members

		public ArrayList GetCommentListByMessageId(int messageId)
		{
			ArrayList commentList = new ArrayList();

			foreach(DataRow row in _commentTable.Select(string.Format("Message_Id={0}", messageId)))
			{
				commentList.Add(GetCommentFromResultRow(row));
			}
			return commentList;
		}

		public int Insert(Comment comment, int messageId)
		{
			_oId++;
			DataRow newRow = _commentTable.NewRow();
			
			newRow["Id"] = _oId;
			newRow["Body"] = comment.Body;
			newRow["PostedByUserName"] = comment.PostedByUserName;
			newRow["PostedByUserId"] = comment.PostedByUserId;
			newRow["Date"] = comment.Date;
			newRow["Author_Id"] = comment.Author.Id;
			newRow["Message_Id"] = messageId;

			_commentTable.Rows.Add(newRow);

			return _oId;
		}

		public void Delete(int id)
		{
			DataRow row = FindCommentDataRow(id);
			if(row!=null)
			{
				_commentTable.Rows.Remove(row);
				_commentTable.AcceptChanges();
			}
		}

		#endregion

		private DataRow FindCommentDataRow(int id)
		{
			foreach(DataRow row in _commentTable.Rows)
			{
				if(DataConverter.GetInteger(row["Id"])==id)
					return row;
			}
			return null;
		}

		private Comment GetCommentFromResultRow(DataRow row)
		{
			return new Comment(DataConverter.GetInteger(row["Id"]), DataConverter.GetString(row["Body"]), DataConverter.GetString(row["PostedByUserName"]), DataConverter.GetString(row["PostedByUserId"]), DataConverter.GetDateTime(row["Date"]), MockProfileAccessor.Instance.Get(DataConverter.GetInteger(row["Author_Id"])));
		}
	}
}
